package com.lanou.dllo.soccernews.fragment.homelinefragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.lanou.dllo.soccernews.R;
import com.lanou.dllo.soccernews.adapter.HeadlineViewpageAdapter;
import com.lanou.dllo.soccernews.adapter.RecommendAdapter;
import com.lanou.dllo.soccernews.bean.HeadLineBean;
import com.lanou.dllo.soccernews.bean.greendao.ArticlesEntity;
import com.lanou.dllo.soccernews.bean.greendao.RecommendEntity;
import com.lanou.dllo.soccernews.database.ArticlesDBhelp;
import com.lanou.dllo.soccernews.database.RecommendDBhelp;
import com.lanou.dllo.soccernews.detailActivty.DetailRecommendPageActivity;
import com.lanou.dllo.soccernews.utils.MyItemOnClickListener;
import com.lanou.dllo.soccernews.utils.NetworkAvailableUtils;
import com.lanou.dllo.soccernews.view.DividerItemDecoration;
import com.lanou.dllo.soccernews.volley.VolleySingleton;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/24.
 */
public class HeadlineFragment extends Fragment {
    private RecommendDBhelp recommendDBhelp;
    private ArticlesDBhelp articlesDBhelp;
    private List<RecommendEntity> recommendEntities;
    private ViewPager pager;
    private HeadlineViewpageAdapter pageradapter;
    private RecyclerView recyclerView;
    private RecommendAdapter recommendAdapter;
    private VolleySingleton volleySingleton;
    private Handler handler;
    private RecyclerViewHeader viewHeader;
    private int currentItem = 0;
    private int maxItem = 0;
    private RelativeLayout loading;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            currentItem++;
            currentItem++;
            pager.setCurrentItem(currentItem % maxItem);
            handler.postDelayed(runnable, 4000);

        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_headline, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //布局初始化
        loading = (RelativeLayout) view.findViewById(R.id.loading);

        viewHeader = (RecyclerViewHeader) view.findViewById(R.id.hearder);
        pager = (ViewPager) view.findViewById(R.id.headline_viewpage);
        recyclerView = (RecyclerView) view.findViewById(R.id.article_rcview);
        pageradapter = new HeadlineViewpageAdapter(getChildFragmentManager());
        LinearLayoutManager lm = new LinearLayoutManager(getContext());
        lm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(lm);

        viewHeader.attachTo(recyclerView, true);
        handler = new Handler();
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        recommendAdapter = new RecommendAdapter();
        volleySingleton = VolleySingleton.getInstance();//init();

        recommendDBhelp = RecommendDBhelp.getInstance();
        articlesDBhelp = ArticlesDBhelp.getInstance();


    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //添加数据
        pager.setOffscreenPageLimit(3);
        pager.setAdapter(pageradapter);
        recyclerView.setAdapter(recommendAdapter);


        if (NetworkAvailableUtils.isNetworkAvailable(getActivity())) {
            loading.setVisibility(View.VISIBLE);
            Toast.makeText(getActivity(), "当前有可用网络！", Toast.LENGTH_LONG).show();

            new Handler().postDelayed(new Runnable() {
                String url = "https://api.dongqiudi.com/tabs_static/2/iphone/1.json";

                @Override
                public void run() {


                    getFromIntenetData(url);//网络加载

                    loading.setVisibility(View.GONE);
                }
            }, 6000);

        } else {
            Toast.makeText(getActivity(), "当前没有可用网络！", Toast.LENGTH_LONG).show();
            recommendEntities = recommendDBhelp.getRecommentEntity();
            List<ArticlesEntity> articlesEntities = articlesDBhelp.getArticlesEntity();

            if (recommendEntities != null && recommendEntities.size() > 0
                    && articlesEntities != null && articlesEntities.size() > 0) {
                pageradapter.addData(recommendEntities);
                recommendAdapter.addData(articlesEntities);
                maxItem = recommendEntities.size();
                handler.postDelayed(runnable, 4000);
            }
        }

        //加载数据

//        new Handler().postDelayed(new Runnable() {
//            String url = "https://api.dongqiudi.com/tabs_static/2/iphone/1.json";
//
//            @Override
//            public void run() {
//                loading.setVisibility(View.VISIBLE);
//                recommendEntities = recommendDBhelp.getRecommentEntity();
//                List<ArticlesEntity> articlesEntities = articlesDBhelp.getArticlesEntity();
//
//                if (recommendEntities != null && recommendEntities.size() > 0
//                        && articlesEntities != null && articlesEntities.size() > 0) {
//                    pageradapter.addData(recommendEntities);
//                    recommendAdapter.addData(articlesEntities);
//                    maxItem = recommendEntities.size();
//                    handler.postDelayed(runnable, 4000);
//                } else {
//                    getFromIntenetData(url);//网络加载
//                }
//                loading.setVisibility(View.GONE);
//            }
//        }, 3000);


        recommendAdapter.setOnItemClickListener(new MyItemOnClickListener() {
            @Override
            public void onItemClick(ArticlesEntity recommendEntity) {
                Intent intent = new Intent(getActivity(), DetailRecommendPageActivity.class);

                intent.putExtra("id", recommendEntity.getId());
                Log.i("lanou00", recommendEntity.getId() + "快快快快快");
                startActivity(intent);
            }
        });
    }

    private void getFromIntenetData(String url) {
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        HeadLineBean hl = gson.fromJson(response, HeadLineBean.class);
                        if (hl != null) {
                            List<RecommendEntity> recommendEntityList = hl.getRecommend();
                            List<ArticlesEntity> articlesEntities = hl.getArticles();
                            // 头条的viewpager
                            if (recommendEntityList != null && recommendEntityList.size() > 0) {
                                pageradapter.addData(recommendEntityList);

                                //添加到数据库中
                                recommendDBhelp.deleteAll();
                                recommendDBhelp.addRecommendEntity(recommendEntityList);


                                maxItem = recommendEntityList.size();
                                handler.postDelayed(runnable, 4000);

                            }
                            //头条下的列表
                            if (articlesEntities != null && articlesEntities.size() > 0) {
                                recommendAdapter.addData(articlesEntities);
                                articlesDBhelp.delete();

                                articlesDBhelp.addArticlesEntity(articlesEntities);
                            }
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        volleySingleton.addRequest(request);
    }


    //判断是否有网络

//    public boolean isNetworkAvailable() {
//        //获取手机所有链接管理对象(wife  net)
//        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
//        if (connectivityManager == null) {
//            return false;
//        } else {
//            //获取NetWorkInfo对象
//            //  Network[] networkInfos = connectivityManager.getAllNetworks();
//            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
//
//            if (networkInfo != null && networkInfo.length > 0) {
//                for (int i = 0; i < networkInfo.length; i++) {
//                    System.out.println(i + "===状态===" + networkInfo[i].getState());
//                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
//                    // 判断当前网络状态是否为连接状态
//                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
//                        return true;
//                    }
//                }
//            }
//
//        }
//        return false;
//    }


}
